package com.chalk.config.security;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * ClassName: SecurityPasswordUtil
 *
 * @author L.G
 * @Description 加密工具类
 * @email lg10000@126.com
 * @date 2018年9月11日 下午4:13:34
 */
public class SecurityPasswordUtil {

    private static final PasswordEncoder PASSWORD_ENCODER = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    /**
     * {bcrypt} 加密的特征码
     */
    public static final String BCRYPT = "{bcrypt}";

    /**
     * {MD5} 加密的特征码
     */
    public static final String MD5 = "{MD5}";

    /**
     * {bcrypt}加密,建议使用此方式加密
     *
     * @param plaintext 待加密内容
     * @return 加密数据
     */
    public static String encrypt(String plaintext) {
        return PASSWORD_ENCODER.encode(plaintext).replace(BCRYPT, "");
    }

    /**
     * {MD5}加密
     *
     * @param plaintext 待加密内容
     * @return 加密数据
     */
    public static String md5Encrypt(String plaintext) {
        return DigestUtils.md5Hex(plaintext);
    }

    /**
     * 解密
     *
     * @param rawPassword     原密码
     * @param encodedPassword 加密密码
     * @return 是否匹配
     */
    public static boolean decrypt(String rawPassword, String encodedPassword) {
        return PASSWORD_ENCODER.matches(rawPassword, encodedPassword);
    }

    public static void main(String[] args) {
        System.out.println(encrypt("chuang-an-security:security"));
        System.out.println(encrypt("123abc"));
        System.out.println(decrypt("chuang-an-security:security", BCRYPT + "$2a$10$zgaO7vhWR4MADd/MHV7wluMbq4niWkKwnLQRyNx/zQI0stGbChtzW"));
        System.out.println(decrypt("123abc", BCRYPT + "$2a$10$MON6wv3riV9BQMkogoQwsOwRckVxGQw0O7IO0.ORat2ehKmyJxefm"));
        System.out.println(decrypt("818181", MD5 + "43792212c74aebba7b8dabd99b485ae3"));
        System.out.println(md5Encrypt("818181"));
    }

}
